//
//  MYPhotosView.m
//  奇闻
//
//  Created by 似水灵修 on 14-11-30.
//  Copyright (c) 2014年 MingYueGuCheng. All rights reserved.
//

#import "MYPhotosView.h"
#import "MYPhotoView.h"
#import "MJExtension.h"
#import "MYPhoto.h"

#import "MJPhoto.h"
#import "MJPhotoBrowser.h"
//相册最大容量
#define MYPhotoCount 9
@implementation MYPhotosView
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 添加所有的子控件,一开始就创建9个
        for (int i = 0; i < MYPhotoCount; i++) {
            MYPhotoView *photoView = [[MYPhotoView alloc] init];
            photoView.tag = i;
            [photoView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)]];
            [self addSubview:photoView];
        }
    }
    return self;
}
- (void)tapGesture:(UITapGestureRecognizer *)gesture
{
    UIView *view = gesture.view;
    //弹出图片浏览器
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = view.tag;
    NSMutableArray *arrM = [NSMutableArray array];
    
    for (MYPhoto *p in self.pic_urls) {
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.srcImageView = (UIImageView *)view;
        //使用清晰或动态图片
        NSString *urlStr = p.thumbnail_pic.absoluteString;
        urlStr =[urlStr stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
        photo.url = [NSURL URLWithString:urlStr];
        [arrM addObject:photo];
    }
    browser.photos = arrM;
    [browser show];
}
// 一有新的cell出现的时候都会调用
// 注意:这里不能每次都创建新的,并且添加上去,因为这个方法会总是调用
- (void)setPic_urls:(NSArray *)pic_urls
{
    _pic_urls = pic_urls;
    if (pic_urls.count) {
        for (int i = 0; i < pic_urls.count; i++) {
            MYPhotoView *photoView = self.subviews[i];
            MYPhoto *photo = self.pic_urls[i];
            photoView.photo = photo;
        }
    }
}
//计算所有子控件的尺寸
- (void)layoutSubviews
{
    [super layoutSubviews];
    //所有的列数
    int cols = (_pic_urls.count == 4) ? 2 : 3;
    int col = 0;
    int row = 0;
    CGFloat x = 0;
    CGFloat y = 0;
    // 9 _pic_urls->6 0 1 2 3 4 5
    for (int i = 0; i < MYPhotoCount; i++) {
        MYPhotoView *imageView = self.subviews[i];
        // 获取当前第几列
        col = i % cols;
        row = i / cols;
        x = col * (MYPhotoWH + MYPhotoMargin);
        y = row * (MYPhotoWH + MYPhotoMargin);
        imageView.frame = CGRectMake(x, y, MYPhotoWH, MYPhotoWH);
        
         // 判断如果i>_pic_urls.count,就隐藏imageView
        if (i >= _pic_urls.count) {// 3  0 1 2->no 4 yes
            imageView.hidden = YES;
        }
        else {
            imageView.hidden = NO;
        }
    }
}
@end
